package cn.lentme.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import cn.lentme.app.base.BaseActivity;
import cn.lentme.app.component.utils.HttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PaperHomeActivity extends BaseActivity {

    private Button btnRead, btnEdit;
    private ImageButton back_btn;
    private TextView hitokitoText;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paper_home);

        initView();
        initContent();
    }

    private void initContent(){
        requireHitokito();
    }

    private void initView(){
        hitokitoText = this.findViewById(R.id.hitokoto_content);

        btnEdit = this.findViewById(R.id.paper_home_btn_edit);
        btnRead = this.findViewById(R.id.paper_home_btn_read);
        back_btn = this.findViewById(R.id.paper_home_back_btn);

        back_btn.setOnClickListener(view ->{
            onBackPressed();
        });

        btnEdit.setOnClickListener(view -> {
            startActivity(new Intent(this, PaperEditActivity.class));
            animFade();
        });

        btnRead.setOnClickListener(view -> {
            startActivity(new Intent(this, PaperReadActivity.class));
            animFade();
        });
    }

    private void requireHitokito(){
        new Thread(() -> {
            OkHttpClient client = HttpUtil.client;
            Request request = new Request.Builder()
                    .url("https://v1.hitokoto.cn")
                    .build();
            try(Response response = client.newCall(request).execute()){
                String content = "";
                if(response.code() == 200){
                    JSONObject json = JSONObject.parseObject(response.body().string());
                    content = json.getString("hitokoto");
                }
                else{
                    content = "code: " + "200, " + response.message();
                }

                final String finalContent = content;
                handler.post(()->{
                    hitokitoText.setText(finalContent);
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
